//
// Created by 张闳 on 2021/12/5.
//

#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "randomstr.h"

char *get_random_string(int random_type, int length) {
    if (length == 0)
        return NULL;
    char numbers[10] = "0123456789";
    char hex[16] = "0123456789abcdef";
    char alpha[52] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char alpha_num[62] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char *rand_str = malloc(length + 1);
    memset(rand_str, 0, length + 1);
    srand((unsigned int) time((time_t *) NULL));
    for (int i = 0; i < length; i++) {
        switch (random_type) {
            case RANDOM_NUMBER:
                *(rand_str + i) = numbers[rand() % 10];
                break;
            case RANDOM_HEX:
                *(rand_str + i) = hex[rand() % 16];
                break;
            case RANDOM_ALPHABET:
                *(rand_str + i) = alpha[rand() % 52];
                break;
            case RANDOM_ALPHABET_NUM:
                *(rand_str + i) = alpha_num[rand() % 62];
                break;
        }
    }
    return rand_str;
}